<template>
  <view class="container screen-width">
    <view class="header u-flex">
      <u-icon @click="backPage" class="u-m-r-40" size="34" name="arrow-left" color="#fff"></u-icon>
      <u-search v-model="name" :show-action="false" @search="handleSearch" @clear="handleClear"></u-search>
    </view>
    <view class="body">
      <view class="areaList filter u-flex">
        <span>
          <input type="text" :value="address ? address : '地区'" @tap="showArea" :disabled="showCity" />
          <image src="../../static/proty/botton_icon.png" mode />
        </span>
        <span>
          <input
            type="text"
            :value="params.startYear ? params.startYear : '时间'"
            @tap="dateShow = true"
            disabled
          />
          <image src="../../static/proty/botton_icon.png" mode />
        </span>
      </view>
      <view class="list-header u-flex">
        <view class="list-header-item u-text-left" style="width: 300rpx">申报单位</view>
        <view class="list-header-item u-text-center" style="width: 252rpx">项目名称</view>
        <view class="list-header-item u-text-center" style="width: 138rpx">通过年份</view>
      </view>
      <scroll-view class="list" :scroll-y="true" @scrolltolower="fetchData()">
        <view
          class="list-item list-header"
          v-for="(item, index) in list"
          :key="index"
          :style="
            'background:' + (index % 2 == 0 ? '#f8f8f8' : '#ffffff') + ';'
          "
        >
          <view class="u-flex">
            <view
              class="list-header-item u-text-left"
              style="width: 300rpx; color: #1678ff"
              @click="toCompanyDetail(item)"
            >{{ item.companyName }}</view>
            <view
              class="list-header-item u-text-center"
              style="width: 252rpx; color: #ff7648"
            >{{ item.projectName }}</view>
            <view
              class="list-header-item u-text-center"
              style="width: 138rpx"
            >{{ item.particularYear }}</view>
          </view>
        </view>
        <u-loadmore
          style="width: 100%;  margin-top: 15rpx;  padding-right: 30rpx"
          :status="status"
        />
      </scroll-view>
    </view>
    <!-- 地区选择 -->
    <!-- 地区 -->
    <van-popup v-model="isshowArea" position="bottom" :style="{ height: '50%' }">
      <!-- <van-area @confirm="affirm" @cancel="cancel" title="地区" :area-list="areaList" :value="address"
      :columns-placeholder="['请选择', '请选择', '请选择']" />-->
      <view class="popup">
        <view class="picker-btn">
          <view class="left" @click="cancel">取消</view>
          <view class="right" @click="affirm">确定</view>
        </view>
        <picker-view :indicator-style="indicatorStyle" :value="valueArr" @change="bindCityChange">
          <picker-view-column>
            <view class="item" v-for="(item,index) in provinceList[0]" :key="index">{{ item }}</view>
          </picker-view-column>
          <picker-view-column v-if="this.provinceList[0][valueArr[0]]">
            <view class="item" v-for="(item,index) in provinceList[1][0]" :key="index">{{ item }}</view>
          </picker-view-column>
          <picker-view-column v-if="this.provinceList[0][valueArr[0]]">
            <view class="item" v-for="(item,index) in provinceList[2][0]" :key="index">{{ item }}</view>
          </picker-view-column>
        </picker-view>
      </view>
    </van-popup>
    <rangeDatePick
      :show="dateShow"
      start="1987"
      :end="endTime"
      @change="handleDateChange"
      themeColor="#4C83D6"
      fields="year"
      @cancel="dateShow = false"
    ></rangeDatePick>
    <Festival></Festival>
  </view>
</template>

<script>
import { getList, getArea } from "../../util/api/project";
import rangeDatePick from "@/components/pyh-rdtpicker/pyh-rdtpicker.vue";

export default {
  data() {
    return {
      address: "",
      isshowArea: false,
      name: "",
      list: [],
      areaList: [],
      params: {
        startYear: null,
        endYear: null,
        province: null,
        city: null,
        area: null,
        pageIndex: 0,
        pageSize: 20,
        projectName: null
      },
      areaShow: false,
      dateShow: false,
      status: "loadmore",
      endTime: String(new Date().getFullYear()),
      indicatorStyle: `height: ${Math.round(
        uni.getSystemInfoSync().screenWidth / (750 / 100)
      )}px;`,
      valueArr: [0, 0, 0], // 用于判断当前滑动的是哪一列

      provinceList: [[], [], []],
      province: ""
    };
  },
  components: { rangeDatePick },
  computed: {
    showCity() {
      let params = this.$store.state.cityInfo;
      // params.city = '东莞市'
      if (params.city === "" && params.province === "") {
        return true;
      } else {
        this.address = params.city;
        return false;
      }
    }
  },
  onLoad(option) {
    let { title } = option;
    this.name = title;
    this.params.projectName = title;
    this.address = uni.getStorageSync("city");
    this.params.city = uni.getStorageSync("city");
    this.fetchData(true);
    this.initLoadArea();
  },
  onHide() {
    this.params.province = "";
    this.params.city = "";
    this.params.area = "";
  },
  methods: {
    // 去公司详情
    toCompanyDetail(item) {
      uni.navigateTo({
        url: `/pages/enterpriseDetails/brand_detail?id=${item.companyId}&type=1&name=${item.companyName}&liIndex=0&showNew=true`
      });
    },
    bindCityChange(e) {
      const val = e.detail.value;
      console.log(e, val);
      if (this.valueArr[0] !== val[0]) {
        this.loadCity(this.provinceList[0][val[0]]);
      } else if (this.valueArr[1] !== val[1]) {
        this.loadArea(this.provinceList[1][0][val[1]]);
      } else if (this.valueArr[2] !== val[2]) {
        // console.log(this.provinceList[2][0][val[2]])
      }
      this.valueArr = val;
    },
    // 进入页面省份查询
    async initLoadArea() {
      let params = {
        type: 3, // 类型(政策通知:0 政策解读:1 部门:2 项目:3)
        city: "", // 城市
        province: "" //省份
      };
      const data = await this.$get(
        "/bmj-api/api/pms/pmsPolicyNotice/selectByTypeRegion",
        params
      );
      this.provinceList[0] = data.result;
      await this.loadCity(data.result[0]);
    },
    // 加载城市
    async loadCity(province) {
      this.province = province;
      let params = {
        type: 3, // 类型(政策通知:0 政策解读:1 部门:2 项目:3)
        city: "", // 城市
        province: province //省份
      };
      const data = await this.$get(
        "/bmj-api/api/pms/pmsPolicyNotice/selectByTypeRegion",
        params
      );
      var arr = [];
      data.result.forEach(item => {
        arr.push(item);
      });
      this.provinceList[1].splice(0, 1, arr);
      this.provinceList[1][0].unshift("请选择");
      await this.loadArea(data.result[0]);
    },
    // 加载地区
    async loadArea(city) {
      let params = {
        type: 3, // 类型(政策通知:0 政策解读:1 部门:2 项目:3)
        city: city, // 城市
        province: this.province //省份
      };
      const data = await this.$get(
        "/bmj-api/api/pms/pmsPolicyNotice/selectByTypeRegion",
        params
      );
      var arr = [];
      data.result.forEach(item => {
        arr.push(item);
      });
      this.provinceList[2].splice(0, 1, arr);
      this.provinceList[2][0].unshift("请选择");
      console.log("区域数据", this.provinceList[2]);
    },

    // 显示弹出层(地区)
    showArea() {
      if (this.showCity) {
        this.isshowArea = true;
      } else {
        this.showArea = false;
      }
    },
    // 确认按钮(地区)
    affirm(res) {
      this.oldAddress = this.address;

      console.log(this.valueArr);
      this.params.province = this.provinceList[0][this.valueArr[0]];
      this.params.city = this.provinceList[1][0][this.valueArr[1]];
      this.params.area = this.provinceList[2][0][this.valueArr[2]];
      let arr = [];
      if (this.params.province) {
        arr.push(this.params.province);
      }
      if (this.params.province && this.params.city) {
        arr.push(this.params.province);
        arr.push(this.params.city);
      }
      if (this.params.province && this.params.city && this.params.area) {
        arr.push(this.params.province);
        arr.push(this.params.city);
        arr.push(this.params.area);
      }
      let arrLen = Array.from(new Set(arr));

      for (let i = 0; i < arrLen.length; i++) {
        if (arrLen[i] === "请选择") {
          arrLen.splice(i, 1);
        }
      }
      console.log(arrLen, arrLen.length);

      if (arrLen.length == 1) {
        (this.params.area = ""),
          (this.params.city = ""),
          (this.params.province = arrLen[0]);
      } else if (arrLen.length == 2) {
        // this.dataItem.province = arr[arr.length - 2].name;
        // this.dataItem.city = arr[arr.length - 1].name;
        (this.params.province = arrLen[0]),
          (this.params.area = ""),
          (this.params.city = arrLen[1]);
      } else if (arrLen.length == 3) {
        // this.dataItem.province = arr[0].name;
        // this.dataItem.city = arr[1].name;
        // this.dataItem.area = arr[arr.length - 1].name;
        (this.params.province = arrLen[0]),
          (this.params.city = arrLen[1]),
          (this.params.area = arrLen[2]);
      } else {
        this.cancel(); // 空数组
        return;
      }
      this.address = arrLen.pop();

      this.cancel();
      if (this.currentItem == 0) {
        this.getNotifyList = [];
        this.pageNo0 = 0;
      } else {
        this.scrambleList = [];
        this.pageNo1 = 0;
      }
      this.fetchData(true);
    },
    // 取消按钮(地区,部门)
    cancel(mark) {
      this.isshowArea = false;
    },
    // 返回上一级
    backPage() {
      uni.navigateBack({
        delta: 2
      });
    },
    handleClear() {
      this.name = "";
      delete this.params.projectName;
      this.fetchData(true);
    },
    handleSearch() {
      if (this.name) {
        this.params.projectName = this.name;
      } else {
        delete this.params.projectName;
      }
      this.fetchData(true);
    },
    fetchData(reset = false) {
      if (reset) {
        this.resetPagination();
      }
      this.status = "loading";
      uni.showLoading();
      getList(this.params).then(res => {
        if (res.code == 10001) {
          uni.hideLoading();
          // 登录失效
          uni.showModal({
            title: "提示",
            content: "请先登录后,再操作",
            success: function(res) {
              if (res.confirm) {
                // console.log("用户点击确定");
                uni.setStorageSync("pageUrl", window.location.href);
                uni.navigateTo({
                  url: "/pages/login/index"
                });
              } else if (res.cancel) {
                // console.log("用户点击取消");
                uni.navigateBack({
                  delta: 2
                });
              }
            }
          });
        } else if (res.retCode == 0) {
          uni.hideLoading();
          console.log(res);
          let records = res.data.content;
          // uni.stopPullDownRefresh();
          if (!records.length) {
            this.status = "nomore";
            return;
          }
          this.list = reset ? records : this.list.concat(records);
          this.params.pageIndex += 1;
          this.status = "loadmore";
        }
      });
    },
    resetPagination() {
      this.params.pageIndex = 1;
      this.list = [];
      this.status = "loadmore";
    },
    // confirm(e) {
    //   this.params = Object.assign(this.params, {
    //     province: e[0]["value"],
    //     city: e[1]["value"],
    //     area: e[2]["value"],
    //   });
    //   this.fetchData(true);
    // },
    handleDateChange(e) {
      this.params = Object.assign(this.params, {
        startYear: e[0],
        endYear: e[1]
      });
      this.fetchData(true);
      this.dateShow = false;
    },
    handleAreaArr(arr, field = "province") {
      return arr.map(v => {
        var fieldName = this.findNextFieldName(field);
        var value;
        if (fieldName) {
          value = v[fieldName];
        } else {
          value = v;
        }

        var _arr = { label: value, value };
        var nextField = this.findNextField(field);
        if (v[nextField] && v[nextField].length > 0) {
          _arr["children"] = this.handleAreaArr(v[nextField], nextField);
        }
        return _arr;
      });
    },
    findNextField(field) {
      switch (field) {
        case "province":
          return "city";
        case "city":
          return "area";
        case "area":
          return null;
      }
    },
    findNextFieldName(field) {
      switch (field) {
        case "province":
          return "province";
        case "city":
          return "name";
        case "area":
          return null;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.popup {
  height: fit-content;
  width: 100%;
  background: #fff;
}

.picker-btn {
  display: flex;
  height: 100upx;
  width: 100%;
  line-height: 100upx;
  background: #fff;
  font-size: 34upx;
  z-index: 1;
  border-bottom: 1rpx solid #f8f8f8;

  .left {
    flex: 1;
    color: #0076ff;
    padding-left: 40upx;
    box-sizing: border-box;
  }

  .right {
    flex: 1;
    text-align: right;
    padding-right: 40upx;
    color: #fe4533;
    box-sizing: border-box;
  }
}

picker-view {
  width: 100%;
  height: 500rpx;
  display: relative;
}
.item {
  line-height: 100rpx;
  text-align: center;
}
.container {
  height: 100%;
}

.header {
  height: 120rpx;
  background: #2862ad;
  padding-left: 34rpx;
  padding-right: 54rpx;
}
.body {
  height: calc(100% - 120rpx);

  .list-header {
    background: #fff;
    padding: 0 30rpx;
    padding-top: 24rpx;
    padding-bottom: 22rpx;
    min-height: 80rpx;
  }

  .list {
    height: calc(100% - 200rpx);

    &-item {
      padding: 24rpx 30rpx 22rpx 30rpx;
    }
  }

  .filter {
    padding: 30rpx;
    color: #1678ff;
    height: 120rpx;

    &-box {
      height: 56rpx;
      background: #fff;
      margin-right: 40rpx;
      padding: 0 34rpx;
      border-radius: 8rpx;
    }
  }
}
.areaList {
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  height: 120rpx;

  span {
    height: 80rpx;
    background-color: #fff;
    margin-right: 50rpx;
    display: flex;
    padding: 10rpx 10rpx;
    align-items: center;

    image {
      width: 20rpx;
      height: 14rpx;
      margin-left: 20rpx;
    }

    input {
      width: 140rpx;
      font-size: 25rpx;
      color: #44a2ff;
    }
  }
}
</style>
